/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : pop_email.js
*  Description  : 동반자 알림 이메일 발송
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description
*  ----------  --------  -------------------------------------------------------- 
*  2012-05-08  김효순    Created.  
*  2012-05-08  김효순    Complete.  
*******************************************************************************/

jQuery(function($){
	// 받는사람
	function clsReceive()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"NOVALUE": "받는사람을 입력해 주십시요."
			, "OVERFLOW": "한번에 5명까지 발송 가능합니다."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsReceive.prototype = {
		_init: function(){
			var $layer = $("div.pop_email tr:eq(0) input:text");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, valid: function(){
			var ar = this.getValue().split(";");
			for(var i=0, cnt=0;i<ar.length;i++){
				if(ar[i].trim()) cnt++;
			}
			
			this.errMsg = null;
			if(this.getValue().trim() == ""){
				this.errMsg = "NOVALUE";
				return false;
			}else if(cnt > 5){
				this.errMsg = "OVERFLOW";
				return false;
			}
			
			return true;
		}
		, getError: function(){
			if(this.errMsg) return this._ERRMSG[this.errMsg];
			else return null;
		}
		, focus: function(){
			this.$getLayer().trigger("focus");
		}
		, getValue: function(){
			return this.$getLayer().val();
		}
		, appendValue: function(val){
			var v = this.getValue();
			
			if(v) v+=";";
			this.$getLayer().val(v+val);
		}
	}
	
	// 제목
	function clsTitle()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"NOVALUE": "제목을 입력해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsTitle.prototype = {
		_init: function(){
			var $layer = $("div.pop_email tr:eq(1) input:text");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, valid: function(){
			this.errMsg = null;
			if(this.getValue().trim() == ""){
				this.errMsg = "NOVALUE";
				return false;
			}
			
			return true;
		}
		, getError: function(){
			if(this.errMsg) return this._ERRMSG[this.errMsg];
			else return null;
		}
		, focus: function(){
			this.$getLayer().trigger("focus");
		}
		, getValue: function(){
			return this.$getLayer().val();
		}
	}
	
	// 부킹메시지
	function clsNote()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"NOVALUE": "메세지를 입력해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsNote.prototype = {
		_init: function(){
			var $layer = $("div.pop_email tr:eq(2) textarea");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, valid: function(){
			this.errMsg = null;
			if(this.getValue().trim() == ""){
				this.errMsg = "NOVALUE";
				return false;
			}
			
			return true;
		}
		, getError: function(){
			if(this.errMsg) return this._ERRMSG[this.errMsg];
			else return null;
		}
		, focus: function(){
			this.$getLayer().trigger("focus");
		}
		, getValue: function(){
			return this.$getLayer().val();
		}
	}
	
	// 예약정보
	function clsReserveInfo()
	{
		this._HTMLDom = null;
		this.infoData = null;
		
		this._init();
	}
	
	clsReserveInfo.prototype = {
		_init: function(){
			var $layer = $("div.reserve_view_bg");

			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("ul.r_event_list li:first").clone(true)
			}
			
			this.setInfo({
				"이벤트리스트": []
			});
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setInfo: function(thisData){
			this.infoData = thisData;
			this.display();
		}
		, display: function(){
			var $layer = this.$getLayer();
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			$layer.find("p.golf_d span:eq(0)").html("<em>" + this.infoData["골프장명"] + "</em> " + this.infoData["코스명"]);
			$layer.find("p.golf_d span:eq(1)").html(this.infoData["홀명"]);
			$layer.find("p.res_date").contents().eq(0).before(this.infoData["날짜"] + ". " + this.infoData["요일"] + "요일").remove();
			$layer.find("p.res_date span").html(this.infoData["시간"]);
			$layer.find("div.res_price div.cost span").html(_util.number_format(this.infoData["원가"]));
			$layer.find("div.res_price div.sale p.s_price span").html(_util.number_format(this.infoData["가격"]));
			
			if(this.infoData["원가"] == this.infoData["가격"]){
				$layer.find("div.res_price div.sale p.ma_right20").html("정상그린피");
				$layer.find("div.res_price>div:lt(2)").hide();
			}
			
			
			$layer.find("p.amount strong.ft_b").html(_util.number_format(this.infoData["보증결제금액"]));
			if(this.infoData["보증결제금액"]){
				$layer.find("p.info").hide();
			}else{
				_util.executeThread(function(){
					return _gf.getMyInfoData();
				}, function(){
					$layer.find("p.info").show().find("strong.name").html(_gf.getMyInfoData()["닉네임"]);
				});
			}
			
			
			$layer.find("ul.ico_list img").each(function(n){
				var s = $(this).attr("src");
				$(this).attr("src", s.replace("_off", "").replace(".png", "_off.png"));
				if(thisClass.infoData["이벤트"]){
					if(thisClass.infoData["이벤트"].indexOf($(this).attr("alt")) != -1) $(this).attr("src", s.replace("_off", ""));
				}
			});
			
			$layer.find("p.tit_event").html(this.infoData["이벤트명"]);
			
			$layer.find("ul.r_event_list").empty();
			
			if(this.infoData["이벤트리스트"].length){
				$layer.find("article.board_list_none").hide();
				
				for(var i=0;i<this.infoData["이벤트리스트"].length;i++){
					$layer.find("ul.r_event_list").append($element.clone(true));
				}
				$layer.find("ul.r_event_list li").each(function(n){
					$(this).html(thisClass.infoData["이벤트리스트"][n]);
				});
			}else{
				$layer.find("article.board_list_none").show();
				$layer.find("ul.r_event_list").hide();
				
				$layer.find("p.tit_event").hide();
			}
		}
		, spinStart: function(){
			var $layer = this.$getLayer();
			
			$layer.find("div.reserve_view").children().hide();
			if($layer.find("div.reserve_view div#tmpSpin").length == 0){
				$layer.find("div.reserve_view").append("<div id='tmpSpin' style='position:relative; width:700px; height:150px;' />");
			}
			$layer.find("div.reserve_view div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this.$getLayer();
			
			$layer.find("div.reserve_view").children().show();
			$layer.find("div.reserve_view div#tmpSpin").hide().spin(false);
		}
		, clone: function(){
			return this.$getLayer().clone(true);
		}
		, getPDate: function(){
			return this.infoData["가승인결제마감일"];
		}
		, getMoney: function(){
			return this.infoData["보증결제금액"];
		}
		, getAgreeYN: function(){
			return this.infoData["결제동의여부"];
		}
	}
	
	// 코스정보
	function clsCourseInfo()
	{
		this._HTMLDom = null;
		this.infoData = null;
		
		this._init();
	}
	
	clsCourseInfo.prototype = {
		_init: function(){
			var $layer = $("article.reserve_detail");
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.children("div.detail_info").children("p:first, div.detail_golf:first").clone(true)
			}
			
			this.setInfo({
				"코스알림": ""
				, "코스리스트":[]
			});
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setInfo: function(thisData){
			this.infoData = thisData;
			this.display();
		}
		, display: function(){
			var $layer = this.$getLayer();
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			if(this.infoData["코스리스트"]){
				$layer.find(">div.detail_info").empty();
				
				for(var i=0;i<this.infoData["코스리스트"].length;i++){
					$layer.find(">div.detail_info").append($element.clone(true));
				}
				$layer.find(">div.detail_info>p").each(function(n){
					var d = thisClass.infoData["코스리스트"][n];
					$(this).find("strong").html(d["코스명"]);
					$(this).next().html('<p class="txt_info">' + d["상세정보"] + '</p>');
					$(this).next().prepend('<img src="' + _gf.filePath2UrlA(d["파일"]) + '" alt="" />').error(function(){
						$(this).remove();
					});
				});
			}
		}
		, spinStart: function(){
			var $layer = this.$getLayer();
			
			$layer.children().hide();
			if($layer.find("div#tmpSpin").length == 0){
				$layer.append("<div id='tmpSpin' style='position:relative; width:700px; height:150px;' />");
			}
			$layer.find("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this.$getLayer();
			
			$layer.find("div#tmpSpin").hide().spin(false);
			$layer.children(":not(div#tmpSpin)").show();
		}
	}
	
	function clsComm()
	{
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){

		}
		// 메일발송
		, emailSubmit: function(arg){
			var thisClass = this;
			
			arg = arg || {}
			arg["콜백"] = arg["콜백"] || function(){}
			
			//ajax
			var serviceName = "reservEmailPopOk";
			var options = {
				"reserv_seq": arg["예약코드"]
				, "title": arg["제목"]
				, "email": arg["받는사람"]
				, "message": encodeURIComponent(arg["메시지"])
			}
			_gf.ajax({
				"sid": "RS001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
				}
				
				arg["콜백"].apply(null, [res]);
			});
			
		}
		// 예약정보
		, getReserveInfo: function(arg){
			var thisClass = this;
			
			arg = arg || {}
			arg["콜백"] = arg["콜백"] || function(){}
			
			//ajax
			var serviceName = "getReservView";
			_gf.ajax({
				"sid": "RS001"
				, "servicename": serviceName
			}, {
				"reserv_seq": arg["예약코드"]
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
					, "결과값": {
						"예약정보": {}
						, "코스정보": {}
					}
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					var obj = items;
					
					var reserv_date = _util.nvl(obj["reserv__date"])+"";
					var reserv_time = _util.nvl(obj["reserv__time"])+"";
					var szEvent = "";
					var pDate = new Date(reserv_date.substr(0, 4), reserv_date.substr(4, 2)-1, reserv_date.substr(6, 2));
					pDate.setDate(pDate.getDate()-5);
					
					var e = [];
					
					var amt_type = {
						"amt": "원"
						, "percent": "%"
					}
										
					if(obj["greenfee__use__yn"] == "Y"){
						szEvent = "그린피";
						e.push("그린피 할인: " + obj["greenfee__discount__amount"] +  amt_type[_util.nvl(obj["greenfee__amt__type"])]);
					}
					
//					if(obj["mileage__use__yn"] == "Y"){
//						e.push("마일리지: " + obj["mileage__amount"] +  obj["mileage__type"]);
//					}
					
					if(obj["cartfee__use__yn"] == "Y"){
						if(szEvent) szEvent += ",";
						szEvent += "카트피";
						e.push("카트피: " + obj["cartfee__discount__amount"]);
					}
					
					if(obj["food__use__yn"] == "Y"){
						if(szEvent) szEvent += ",";
						szEvent += "식사";
						e.push("식사: " + obj["food__discount__amount"]);
					}
					
					if(obj["present__use__yn"] == "Y"){
						if(szEvent) szEvent += ",";
						szEvent += "선물";
						e.push("선물: " + obj["present__content"]);
					}
					
					if(obj["etc__use__yn"] == "Y"){
						if(szEvent) szEvent += ",";
						szEvent += "기타";
						e.push("기타: " + obj["etc__content"]);
					}
					
					res["결과값"]["예약정보"] = {
						"예약코드": arg["예약코드"]
						, "코스코드": "001"
						, "골프장명": _util.nvl(obj["golfclub__name"])
						, "코스명": _util.nvl(obj["course__info__name1"])
						, "홀명": _util.nvl(obj["hole"]) + "H"
						, "날짜": reserv_date.substr(0, 4) + ". " + reserv_date.substr(4, 2) + ". " + reserv_date.substr(6, 2)
						, "요일": _util.nvl(obj["reserv__day"])
						, "시간": reserv_time.substr(0, 2) + ":" + reserv_time.substr(2, 2)
						, "원가": _util.nvl(obj["price"], 0)
						, "가격": _util.nvl(obj["greenfee"], 0) || _util.nvl(obj["price"], 0)
						, "이벤트": szEvent
						, "보증결제금액": _util.nvl(obj["price__pay"], 0)
						, "예약상태": obj["reserv__status"]
						, "결제등급": obj["reserv__paytype"]
						, "가승인결제마감일": pDate
						, "이벤트리스트": e
						, "이벤트명": _util.nvl(obj["event__name"])
						, "결제동의여부": _util.nvl(obj["pay__agree"])
						, "가예약가능여부": _util.nvl(obj["nonpay__yn"])
						, "보증결제가능여부": _util.nvl(obj["pay__yn"])
					}
					
					res["결과값"]["코스정보"] = {
						"코스알림": _util.nvl(obj["course__notice"])
						, "코스리스트": []
					}
					
					for(var i=1;i<4;i++){
						if(_util.nvl(obj["course__info__id" + i])){
							var objCourseList = {
								"코드코드": _util.nvl(obj["course__info__id" + i])
								, "코스명": _util.nvl(obj["course__info__name" + i])
								, "상세정보": _util.nvl(obj["description" + i])
							}
							
							if(obj["course" + i + "__file"]){
								objCourseList["파일"] = _util.nvl(obj["course1__file"][0]["items"]["path"]) + _util.nvl(obj["course1__file"][0]["items"]["save__file__name"])
							}
							
							res["결과값"]["코스정보"]["코스리스트"].push(objCourseList);
						}
					}
				}
				
				arg["콜백"].apply(null, [res]);
			});
		}
	}
	
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objReceive = null;
		this.objTitle = null;
		this.objNote = null;
		this.objReserveInfo = null;
		this.objCourseInfo = null;
		
		this.q_reserve = null;
		this._permitStart = null;
		this.openerControl = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload()
			
			this.objComm = new clsComm();
			this.objReceive = new clsReceive();
			this.objTitle = new clsTitle();
			this.objNote = new clsNote();
			this.objReserveInfo = new clsReserveInfo();
			this.objCourseInfo = new clsCourseInfo();
			
			this._bind();
			this._beforeStart();
			
			document.objUtil.setWindowSize();
		}
		, _preload: function(){
			_gf.spinStart();
			
			this.q_reserve = _util.getParam("q_reserve");
			
			if(opener && opener.document && opener.document.objControl) this.openerControl = opener.document.openerControl;
		}
		, _bind: function(){
			var thisClass = this;
			
			$(document).on("click", "img[alt='보내기'], img[alt='취소'], img['close'], img[alt='발송자 목록에서 선택']", function(){
				var alt = $(this).attr("alt");
				
				switch(alt){
					case "보내기":
						if(!thisClass.objReceive.valid()){
							alert(thisClass.objReceive.getError());
							thisClass.objReceive.focus();
							return;
						}else if(!thisClass.objTitle.valid()){
							alert(thisClass.objTitle.getError());
							thisClass.objTitle.focus();
							return;
						}else if(!thisClass.objNote.valid()){
							alert(thisClass.objNote.getError());
							thisClass.objNote.focus();
							return;
						}
						
						thisClass.emailSubmit();
						break;
					case "발송자 목록에서 선택":
						thisClass.goEmailListPage();
						break;
					case "취소":
					case "close":
						self.close();
						break;
				}
			});
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			_util.executeThread(function(){
				for(var k in thisClass._permitStart){
					if(!thisClass._permitStart[k]) return false;
				}
				
				return true;
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _start: function(){
			var thisClass = this;
			
			// 예약정보
			this.objReserveInfo.spinStart();
			this.objComm.getReserveInfo({
				"예약코드": this.q_reserve
				, "콜백": function(ret){
					thisClass.finishReserveInfo(ret);
				}
			});
		}
		// 발송완료
		, finishEmailSubmit: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			_gf.spinEnd();
			//self.close();
		}
		// 예약정보 완료
		, finishReserveInfo: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
				
			this.objReserveInfo.spinEnd();
			this.objReserveInfo.setInfo(ret["결과값"]["예약정보"]);
			
			this.objCourseInfo.spinEnd();
			this.objCourseInfo.setInfo(ret["결과값"]["코스정보"]);
		}
		// 메일발송
		, emailSubmit: function(){
			var thisClass = this;
			
			_gf.spinStart("sending...");
			this.objComm.emailSubmit({
				"예약코드": this.q_reserve
				, "받는사람": this.objReceive.getValue()
				, "제목": this.objTitle.getValue()
				, "메시지": this.objNote.getValue()
				, "콜백": function(ret){
					thisClass.finishEmailSubmit(ret);
				}
			});
		}
		// 이메일 리스트로부터 메일리스팅 완료
		, closeEmailList: function(w, e){
			if(w) w.close();
			
			this.objReceive.appendValue(e);
		}
		// 발송자목록 이동
		, goEmailListPage: function(){
			var szLink = _ROOT + "/popup/pop_sender.html";
			var winEmailList = window.open(szLink, "winEmailList", "width=600, height=300, scrollbars=0");
			if(winEmailList) winEmailList.focus();
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});